package com.example.java.serializable;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *
 * 在序列化的过程中readObject writeObject 是序列化的方法,如果定义的这两个方法
 * 那么java不会自动序列化对象,而是调用定义的readObject,writeObject来序列化,该方法是私有的,只有可序列化对象能用
 * 实现这个扩展Externalizable,重写writeExternal,readExternal方法,与readObject writeObject的区别是,扩展方法
 * 是公共的方法,对包括超类在内的整个对象的存储和回复负全责.
 */
public class Employee implements Externalizable {

    public Employee()
    {
    }

    public Employee(String n, double s, int year, int month, int day)
    {
        name = n;
        salary = s;
        GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
        hireDay = calendar.getTime();
    }

    public String getName()
    {
        return name;
    }

    public double getSalary()
    {
        return salary;
    }

    public Date getHireDay()
    {
        return hireDay;
    }

    public void raiseSalary(double byPercent)
    {
        double raise = salary * byPercent / 100;
        salary += raise;
    }

    @Override
    public String toString()
    {
        return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
                + "]";
    }

    private String name;
    private double salary;
    private Date hireDay;


    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
        out.writeDouble(salary);
        out.writeLong(hireDay.getTime());

    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

        name = in.readUTF();
        salary = in.readDouble();
        hireDay = new Date(in.readLong());
    }
}
